package com.Jano.controller;

import com.Jano.annotation.LogAnnotation;
import com.Jano.dto.JsonResult;
import com.Jano.model.UserModel;
import com.Jano.service.UserService;
import com.Jano.util.jwt.Constant;
import com.Jano.util.jwt.JwtTokenUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author Administrator
 * @Date: 2022/7/14 14:31
 * @Version 1.0
 */

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping("/login.do")
    public JsonResult login(String userName, String password, HttpSession session) {
        //登陆(校验在service层做,校验不通过直接抛出异常即可)
        UserModel user = userService.findByLogin(userName, password);
        //将对象数据存入session方便切面获取后进行信息提取log日志保存,不仍然使用token的原因不是每一个方法都会返回token
        //然后这个log日志应该是要具有通用性的,session的生命周期会一直持续到会话关闭,所以非常合适用于log日志的处理
        session.setAttribute("sessionUser", user);
        JsonResult jsonResult = new JsonResult();
        //签发token
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constant.JWT_USER_NAME, user.getUsername());
        //签发jwtToken
        String jwtToken = JwtTokenUtil.getAccessToken(user.getId() + "", claims);
        //===================================================
        Logger logger = LoggerFactory.getLogger(getClass());
        logger.info("生成的令牌的载荷==>"+JwtTokenUtil.getClaimsFromToken(jwtToken));
        logger.info("当前生成的jwtToken==>"+jwtToken);
        //===================================================
        //签发refreshToken 时间更长！！！
        String jwtRefreshToken = JwtTokenUtil.getRefreshToken(user.getId() + "", claims);
        //===================================================
        logger.info("生成成的刷新令牌的载荷==>"+JwtTokenUtil.getClaimsFromToken(jwtRefreshToken));
        logger.info("当前生成的jwtRefreshToken==>"+jwtRefreshToken);
        //===================================================
        //最终的结果为签发两个token
        Map<String, Object> result = new HashMap<>();
        result.put(Constant.ACCESS_TOKEN,jwtToken);
        result.put(Constant.REFRESH_TOKEN,jwtRefreshToken);
        jsonResult.setCode(HttpStatus.OK.value());
        jsonResult.setData(result);
        return jsonResult;
    }
}

